import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class _107 {
    static class Solution1 {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            //bfs
            List<List<Integer>> res = new ArrayList<>();
            List<TreeNode> cur = new ArrayList<>();
            if (root != null) cur.add(root);
            while (cur.size() > 0) {
                List<Integer> resItem = new ArrayList<>();
                List<TreeNode> next = new ArrayList<>();
                for (TreeNode node : cur) {
                    resItem.add(node.val);
                    if (node.left != null) next.add(node.left);
                    if (node.right != null) next.add(node.right);
                }
                cur = next;
                res.add(resItem);
            }
            Collections.reverse(res);
            return res;
        }
    }

    static class Solution2 {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            dfs(res, root, 0);
            Collections.reverse(res);
            return res;
        }

        public void dfs(List<List<Integer>> list, TreeNode root, int deep) {
            if (root == null) return;
            if (list.size() == deep) {
                list.add(new ArrayList<>());
            }
            list.get(deep).add(root.val);
            dfs(list, root.left, deep + 1);
            dfs(list, root.right, deep + 1);
        }
    }
}
